<template>
  <component
    :is="elTagNameValue"
    v-bind="item.props"
    :style="style"
    v-model.trim="model[getProp(item.prop)]"
    :data="['tree-select'].includes(item.eTag!) ? itemEnum : []"
    :options="['cascader', 'select-v2'].includes(item.eTag!) ? itemEnum : []"
  >
    <template v-if="item.eTag === 'cascader'" #default="{ data }">
      <span>{{ data[item.fieldNames?.label || 'label'] }}</span>
    </template>
    <template v-if="item.eTag === 'select'">
      <component
        :is="`el-option`"
        v-for="(col, index) in itemEnum"
        :key="index"
        :label="col[item.fieldNames?.label || 'label']"
        :value="col[item.fieldNames?.value || 'value']"
      ></component>
    </template>
    <template v-if="item.eTag === 'radio-group'">
      <component :is="`el-radio`" v-for="(col, index) in itemEnum" :key="index" :value="col[item.fieldNames?.value || 'value']">
        {{ col[item.props.labelKey || 'label'] }}
      </component>
    </template>
    <template v-if="item.eTag === 'radio-button'">
      <component :is="`el-radio-button`" v-for="(col, index) in itemEnum" :key="index" :value="col[item.fieldNames?.value || 'value']">
        {{ col[item.fieldNames?.label || 'label'] }}
      </component>
    </template>
    <template v-if="item.eTag === 'checkbox-group'">
      <component
        :is="`el-checkbox`"
        v-for="col in itemEnum"
        :key="col[item.fieldNames?.value || 'value']"
        :value="col[item.fieldNames?.value || 'value']"
      >
        {{ col[item.fieldNames?.label || 'label'] }}
      </component>
    </template>
  </component>
</template>

<script setup lang="ts" name="Item">
import { getProp } from '@/utils'
interface ItemProps {
  item: EcoForm.Item
  style?: CSSStyleDeclaration
}
const props = defineProps<ItemProps>()
const model = defineModel<Record<string, any>>({ required: true })
const elTagNameValue = computed(() => {
  const val = props.item.eTag
  if ('radio-button' == val) return `el-radio-group`
  return `el-${val || 'input'}`
})
// 接收 enumMap (el 为 select-v2 需单独处理 enumData)
const enumMap = inject('enumMap', ref(new Map()))
const itemEnum = computed(() => {
  // CompAttributes
  let enumData = enumMap.value.get(props.item.props?.enumKey || props.item.prop)
  if (!enumData) return []
  // 返回对象类型
  if (props.item.eTag === 'tree-select') {
    enumData = enumData.map((el: { [key: string]: any }) => {
      return {
        ...el,
        label: el[props.item.fieldNames?.label || 'label'],
        children: el[props.item.fieldNames?.children || 'children'] || []
      }
    })
  }
  return enumData
})
</script>
